<?php

namespace Admin\Controller;

use Common\Model\ChildInfoModel;
use Common\Model\ClinicModel;
use Common\Model\ContactsModel;
use Common\Model\FamilyMemberModel;
use Common\Model\GeneTestShareModel;
use Common\Model\ImModel;
use Common\Model\LiveModel;
use Common\Model\UserDoctorModel;
use Common\Model\UserGravideModel;
use Common\Model\UserModel;
use Admin\Controller\AiController;
use OSS\Core\OssException;

class HelperController extends AiController
{

    /**
     * 获取未下载的通话录音URL列表
     */
    private function getRecordingList()
    {
        $recording_list = D('LetterCdr')->field('id, recordurl')->where(array('is_download' => 1, 'recordurl' => array('neq', '')))->select();
        return $recording_list;
    }

    /**
     * 获取已下载的通话录音存放路径列表
     */
    private function getRecordingPathList()
    {
        $recording_list = D('LetterCdr')->field('id, file_path')->where(array('is_download' => 2, 'file_path' => array('neq', '')))->select();
        return $recording_list;
    }

    /**
     * 删除列表中所有文件
     * @param array $list
     */
    private function deleteLocalRecording($list)
    {
        if (is_array($list)) {
            foreach ($list as $k => $v) {
                unlink($v);
            }
        }
    }

    /**
     * 更新文件上传成功的阿里云下载url
     * @param unknown $list
     */
    private function setOssRecordingUrl($list)
    {
        if (is_array($list)) {
            foreach ($list as $k => $v) {
                $data = array();

                $data['id'] = $v['id'];
                $data['is_download'] = 3;
                $data['oss_url'] = $v['oss_url'];

                D('LetterCdr')->save($data);
            }
        }
    }

    /**
     * 下载列表中文件
     */
    public function downloadRecording()
    {
        set_time_limit(0);

        $recording_list = $this->getRecordingList();
        if (0 === count($recording_list)) return false;

        foreach ($recording_list as $k => $v) {
            $file = get_save_file($v['recordurl'], '/');
            $file = './Public/recording/' . $file;

            $result = http_copy($v['recordurl'], $file);

            if ($result) {
                $data = array(
                    'id' => (int)$v['id'],
                    'is_download' => 2,
                    'file_path' => $file
                );
                D('LetterCdr')->save($data);
            }
        }
    }

    /**
     * 将已经下载的通话录音上传至OSS
     */
    public function uploadOss()
    {
        set_time_limit(0);

        $recording_list = $this->getRecordingPathList();
        if (0 === count($recording_list)) return false;

        $oss = 'http://grjiujiu.oss-cn-hangzhou.aliyuncs.com/';
        $bucket = 'grjiujiu';
        $object = 'recording/';

        vendor('Alioss.samples.Common');
        $oss_client = \Common::getOssClient();

        try {
            $res = $oss_client->doesBucketExist($bucket);
            $exist = $oss_client->doesObjectExist($bucket, $object);
        } catch (OssException $e) {
            return false;
        }

        if (!$res || !$exist) return false;

        $oss_recording_url_list = array();
        $complete_download_list = array();
        foreach ($recording_list as $k => $v) {
            $object_file = $object . get_save_file($v['file_path'], '/');

            try {
                $oss_client->uploadFile($bucket, $object_file, $v['file_path']);
            } catch (OssException $e) {
                $object_file = NULL;
                continue;
            }

            $oss_recording_url = $oss . $object_file;
            $oss_recording_url_list[] = array('id' => (int)$v['id'], 'oss_url' => $oss_recording_url);
            $complete_download_list[] = $v['file_path'];

            $object_file = NULL;
            $oss_recording_url = NULL;
        }

        $this->setOssRecordingUrl($oss_recording_url_list);
        //$this->deleteLocalRecording($complete_download_list);
    }

    #载入地址数据
    public function ajaxArea($id = 0)
    {
        $data = (D('CommArea')->where('pid=' . $id)->order('ord DESC,name ASC')->select()); #rs2select
        echo json_encode($data);
        exit;
    }
       #载入表数据
    public function linkTableName()
    {   
        $tableName=I('tname');
        $pid_file=I('pid_file')?I('pid_file'):'pid';
        $id=I('id')?I('id'):'0';
        $data = (D($tableName)->where($pid_file.'='.$id)->select()); #rs2select
        echo json_encode($data);
        exit;
    }

    // 将超过24小时未接诊的链接取消，设置为过期
    public function cleanInvalidLetter()
    {
        $where = " is_over=1 AND UNIX_TIMESTAMP(NOW())-add_time > 86400";
        D('ClinicLetter')->where($where)->setField('is_over', 0);
    }

    // 每日19:00向医生提示未接诊的患者
    public function clincLetterPush1()
    {
        if (date('H', time()) == 19) {
            $result = S('cl_push');

            if ($result == null) {
                $time = date('Y-m-d', time());
                $result = D('ClinicLetter')->field('count(*) as c, clinic_id')->where(" is_over = 1 and FROM_UNIXTIME(add_time, '%Y-%m-%d') = {$time} ")->group('clinic_id')->select();
                if ($result === null) return false;

                S('cl_push', $result, 7200);
                foreach ($result as $k => $v) {
                    $doctor_id = D('Clinic')->where(array('id' => (int)$v['clinic_id']))->getField('user_id');
//                    $doctor_mobile = D('User')->where(array('id' => (int)$doctor_id))->getField('mobile');
                    $doctor_mobile = D('User')->getUserAttr((int)$doctor_id, 'mobile');

                    $str = "你今天收到了{$v['c']}患者的诊室咨询，现在有时间接诊吗？";
                    D('Push')->addRequest($device_type = 3, $push_type = 2, $target = 'account', $target_value = $doctor_mobile, $title = '新通知', $summary = $str, $body = $str, $ios_ext_parameters = '', $android_open_type = 2, $android_activity = 'com.gr.jiujiudoctor.ReClinicListActivity', $android_ext_parameters = '{"a":"b"}', $level = 0, $info_type = 17);
                    M('WeiboPrompt')->where(array('user_id' => intval($doctor_id)))->setInc('doctor_notice_count');
                }
            } else {
                return false;
            }
        }

        return false;
    }

    // 挂断电话30分钟后，提醒医生写建议
    public function remindDoctorWriteAdvice()
    {
        $sql = "SELECT user_id, clinic_id FROM jj_clinic_letter as a, jj_letter_cdr as b WHERE a.id=b.letter_id AND a.is_over=2 AND UNIX_TIMESTAMP(NOW())-b.add_time >= 1800";
        $result = M()->query($sql);
        $data = date("Y-m-d", time());
        $start_date = strtotime($data);
        $end_date = $start_date + 86400;
        foreach ($result as $k => $v) {
//            $realname = D('User')->where(array('id' => (int)$v['user_id']))->getField('realname');
            $realname = D('User')->getUserAttr((int)$v['user_id'], 'realname');
            $days = get_pregnant_days((int)$v['user_id']);
            $week = self::getWeek($days);

            $doctor_id = D('Clinic')->where(array('id' => (int)$v['clinic_id']))->getField('user_id');
//            $doctor_mobile = D('User')->where(array('id' => (int)$doctor_id))->getField('mobile');
            $doctor_mobile = D('User')->getUserAttr((int)$doctor_id, 'mobile');

            $str = "{$realname}{$week}患者的诊室咨询，请你写建议。";
            D('Push')->remindDoctorWriteAdvice($doctor_id, $doctor_mobile, $str);
        }
    }

    public function noticeGravidePay1()
    {
        $where = " is_over=3 AND UNIX_TIMESTAMP(NOW())-add_time > 86400 AND total<>0.00 ";
        $result = D('ClinicLetter')->where($where)->select();
        $data = date("Y-m-d");
        $start_date = strtotime($data);
        $end_date = $start_date + 86400;

        $user = new UserModel();
        foreach ($result as $k => $v) {
            $doctor_id = D('Clinic')->where(array('id' => (int)$v['clinic_id']))->getField('user_id');

            $doctor_mobile = $user->getUserAttr((int)$doctor_id, 'mobile');
            $doctor_realname = $user->getUserAttr((int)$doctor_id, 'realname');
            $doctor_title_id = $user->getUserAttr((int)$doctor_id, 'title_id');
            $doctor_title = $GLOBALS['titlies'][(int)$doctor_title_id];
            $avatar = $user->getUserAttr((int)$doctor_id, 'avatar');
            $name = $doctor_realname;
            $price = $v['total'];

//            $aep = json_encode(array('name' => $name, 'avatar' => initAvatar($avatar), 'price' => $price, 'title' => $doctor_title));
//            $str = "你有一笔{$price}元的医生咨询，还未付款。";
            /*
            $ios_kv = json_encode(array('remote' => 'pay', 'much' => $price));
            //判断今天是否已经推送了
            $r = M('Push')->where("info_type= 23 AND target_value='{$doctor_mobile}' AND add_time>= $start_date AND add_time<= $end_date")->find();
            if(!$r){
                D('Push')->addRequest($device_type = 3, $push_type = 2, $target = 'account', $target_value = $doctor_mobile, $title = '新通知', $summary = $str, $body = $str, $ios_ext_parameters=$ios_kv, $android_open_type=2,$android_activity='com.gr.jiujiudoctor.ClinicSuccessActivity',$android_ext_parameters=$aep,$level=0,$info_type=23);
            }*/
        }
    }

    private static function getWeek($day)
    {
        $w = intval($day / 7);
        if ($w == 0) {
            return '(+' . $day . ')';
        } else {
            $d = $day % 7;
            if ($d == 0) {
                return '(' . $w . '周)';
            } else {
                return '(' . $w . '周+' . $d . ')';
            }
        }
    }

    /**
     * 官方机器人推送今日知识
     * @param int $clean
     */
    public function officialAiPush($clean = 0)
    {
        set_time_limit(0);

        echo 'over...';
        die;
    }

    /**
     * 大长啾 8:00 推送 今日知识
     * @param int $clean
     * @return string
     */
    public function dcjPushKnowledge($clean = 0)
    {
        set_time_limit(0);

        // 强行清理缓存
        if ($clean == 1) S('dcj_last_gravide_id', null);

        $now_time_hour = date('H', ADD_TIME);
        if ($now_time_hour >= 20 || $now_time_hour < 8) {
            S('dcj_last_gravide_id', null);
            return 'Not to time';
        }

        $last_id = S('dcj_last_gravide_id');
        $last_id = $last_id === false ? 0 : $last_id;

        $users = D('UserGravide')->getAllGravideId($last_id, 100);

        if (count($users) == 0) return 'No data';

        $last_user_obj = end($users);
        S('dcj_last_gravide_id', $last_user_obj['id']);

        foreach ($users as $user) {
            $days = get_pregnant_days((int)$user['id']);
            if (($days >= 0) && ($days <= 280)) {
                // 执行推送 今日知识
                $this->pushKnowledge('big_jiujiu', (int)$days, $user['mobile'], '11111111114');
            }
        }
    }

    /**
     * 啾你妹 14:00 推送 今日知识
     * @param int $clean
     * @return string
     */
    public function jnmPushKnowledge($clean = 0)
    {
        set_time_limit(0);

        // 强行清理缓存
        if ($clean == 1) S('jnm_last_gravide_id', null);

        $now_time_hour = date('H', ADD_TIME);
        if ($now_time_hour >= 20 || $now_time_hour < 14) {
            S('jnm_last_gravide_id', null);
            return 'Not to time';
        }

        $last_id = S('jnm_last_gravide_id');
        $last_id = $last_id === false ? 0 : $last_id;

        $users = D('UserGravide')->getAllGravideId($last_id, 100);
        if (count($users) == 0) return 'No data';

        $last_user_obj = end($users);
        S('jnm_last_gravide_id', $last_user_obj['id']);

        foreach ($users as $user) {
            $days = get_pregnant_days((int)$user['id']);
            if (($days >= 0) && ($days <= 280)) {
                // 执行推送 今日知识
                $this->pushKnowledge('sister_jiujiu', (int)$days, $user['mobile'], '11111111116');
            }
        }
    }

    /**
     * Dr.JoJo 19:30 推送 今日知识
     * @param int $clean
     * @return string
     */
    public function drjPushKnowledge($clean = 0)
    {
        set_time_limit(0);

        // 强行清理缓存
        if ($clean == 1) S('drj_last_gravide_id', null);

        $now_time_hour = date('H', ADD_TIME);
        if ($now_time_hour >= 21 || $now_time_hour < 20) {
            S('drj_last_gravide_id', null);
            return 'Not to time';
        }

        $last_id = S('drj_last_gravide_id');
        $last_id = $last_id === false ? 0 : $last_id;

        $users = D('UserGravide')->getAllGravideId($last_id, 100);
        if (count($users) == 0) return 'No data';

        $last_user_obj = end($users);
        S('drj_last_gravide_id', $last_user_obj['id']);

        foreach ($users as $user) {
            $days = get_pregnant_days((int)$user['id']);
            if (($days >= 0) && ($days <= 280)) {
                // 执行推送 今日知识
                $this->pushKnowledge('doctor_jiujiu', (int)$days, $user['mobile'], '11111111115');
            }
        }
    }

    /**
     * 官方机器人执行推送
     * @param int $week
     * @param string $mobile
     * @param string $account
     */
    private function pushKnowledge($types, $week, $mobile, $account)
    {
        $know = D('Knowledge');
        $know_type = D('KnowledgeType');
        $im = D('Im');

        $robot = array(
            '11111111114' => array('4', '6', '7'),
            '11111111115' => array('1', '3', '5'),
            '11111111116' => array('2', '8', '9'),
        );

        foreach ($robot[$account] as $type) {
            $where = array('week' => $week, 'type' => (int)$type);
            $obj = $know->field('lead, link, image, title')->where($where)->find();
            if ($obj !== null) {

                $image = $obj['image'] == '' ? NEW_DEFAULT_IMAGE : initImageLocal($obj['image']);

                $data = array(
                    'summary' => $obj['lead'],
                    'image' => $image,
                    'url' => $obj['link'],
                );

                if ($obj['title'] == '') {
                    $data['title'] = $know_type->where(array('id' => (int)$type))->getField('name');
                } else {
                    $data['title'] = $obj['title'];
                }
                D('Push')->pushKnowledge($types, $account, $mobile, $data['summary'], $data['image'], $data['url']);
                /*
                $json_data = json_encode($data);
                $im->custmsgPush($account, $mobile, $data['summary'], $json_data);
                */
            }
        }
    }

    /**
     * 测试今日知识推送
     * @param string $mobile
     */
    public function testKnowledgePush($mobile = '18604053412')
    {
        $this->pushKnowledge(100, $mobile, '11111111115');
    }

    /**
     * 每日自动报送当日积分情况汇总数据
     */
    public function userScoreReport()
    {
        $integral_reward = D('IntegralReward');
        $today = get_date(ADD_TIME);
        $now = get_datetime(ADD_TIME);
        $today_time = strtotime($today);
        $yesterday_time = $today_time - 86400;
        $yesterday = get_date($yesterday_time);

        $where = " add_time > {$yesterday_time} AND add_time < {$today_time} ";

        // 累计赠送积分
        $sum_score = $integral_reward->where($where)->sum('number');
        $sum_score = $sum_score == '' ? 0 : $sum_score;

        // 累计赠送用户数
        $sql = "SELECT COUNT(c.counts) c FROM ( SELECT count(*) counts, `id`  FROM `jj_integral_reward`  WHERE `add_time` > {$yesterday_time} AND `add_time` < {$today_time} GROUP BY `user_id` ) c;";
        $result = M()->query($sql);

        $gift_count = $result[0]['c'];

        // 赠送积分交易笔数
        $transaction_count = $integral_reward->where($where)->count();

        $email = 'yuanlf@gerui.org';
        $email2 = 'kq@gerui.org';
        $email3 = 'zixi_han@sina.com';

        $title = '每日自动报送当日积分情况汇总数据';

        $content = <<<EOT
<h3>自动报送{$yesterday}积分情况汇总数据</h3>
<h4>日期: [{$today}]</h4>
<hr />
累计赠送积分: {$sum_score}分 <br />
累计赠送用户数: {$gift_count}人 <br /><br />

赠送积分交易数: {$transaction_count}笔 <br />
本邮件由系统于{$now}自动统计产生 <br />
EOT;

        C('MAIL_HOST', 'smtp.exmail.qq.com');
        C('MAIL_USERNAME', 'hg@gerui.org'); // 你的邮箱名
        C('MAIL_FROM', 'hg@gerui.org');     // 发件人地址
        C('MAIL_PASSWORD', 'Grace520..');   // 邮箱密码
        C('MAIL_FROMNAME', '韩皓光');        // 发件人姓名

        $re = sendEmail($email, $title, $content);
        $re2 = sendEmail($email2, $title, $content);
        $re3 = sendEmail($email3, $title, $content);

        if ($re) {
            echo "{$email} 发送成功<br />";
        } else {
            echo "{$email} 发送失败<br />";
        }

        if ($re2) {
            echo "{$email2} 发送成功<br />";
        } else {
            echo "{$email2} 发送失败<br />";
        }

        if ($re3) {
            echo "{$email3} 发送成功<br />";
        } else {
            echo "{$email3} 发送失败<br />";
        }
        die;
    }

    /**
     * 批量导入用户
     * @param string $file 导入文件
     * @param string $remark 导入备注
     */
    public function importUser($file = '', $remark = '')
    {
        set_time_limit(0);

        if ($file == '') {
            echo 'File Is Null';
            die;
        } else {
            dump($file);
            dump($remark);
            die;
            $content = file_get_contents($_SERVER['DOCUMENT_ROOT'] . '/' . $file);
            $lists = explode(PHP_EOL, $content);

            foreach ($lists as $list) {
                $user = explode('|', trim($list, '|'));
                $this->userAddDb($user, $remark);
            }
        }
    }

    /**
     * 将用户数据插入数据库
     * @param array $userObj 用户信息
     * @param string $remark 导入备注
     */
    private function userAddDb($userObj, $remark)
    {
        die;
    }

    public function updateNickname()
    {
        set_time_limit(0);

        $user_db = D('User');
        $test_nick = D('TestNick');

//        $result = $user_db->field('id,nickname')->where(array('import' => 'FirstBatch'))->select();
        $result = $user_db->field('id,nickname')->where(array('remark' => 'FirstBatch'))->select();
        foreach ($result as $k => $v) {
            $nick_obj = $test_nick->where(array('is_user' => 0))->order('id ASC')->find();
            $user_db->where(array('id' => (int)$v['id']))->setField('nickname', $nick_obj['name']);
            $test_nick->where(array('id' => (int)$nick_obj['id']))->setField('is_user', 1);
        }
    }

    public function updateRegTime()
    {
        $user_db = D('User');

//        $result = $user_db->field('id,reg_time')->where(array('import' => 'FirstBatch'))->select();
        $result = $user_db->field('id,add_time')->where(array('remark' => 'FirstBatch'))->select();
        foreach ($result as $k => $v) {
            $reg_time = mt_rand(1456761600, 1484064000);
            $user_db->where(array('id' => (int)$v['id']))->setField('add_time', $reg_time);
        }
    }

    # 测试
    public function testPushTiroTutorial($mobile = '18604053412')
    {
        $im = new ImModel();

        $summary = 'hi,你好！我是啾啾，你的孕期新朋友。让我带领你，了解一下这里都有哪些好玩意吧！';
        $data = array(
            'summary' => $summary,
            'image' => 'http://oss.jiujiu.gerui.org/Public/uploads/jiujiu_s.png',
            'url' => 'http://h5.jiujiu.gerui.org/index.php?m=Wap&c=TiroTutorial',
            'title' => '啾啾新手教程'
        );
        $json_data = json_encode($data);
        $im->custmsgPush('11111111110', $mobile, $summary, $json_data);
    }

    /**
     * 同步阿里百川数据
     */
    public function syncImData()
    {
        $user = new UserModel();
//        $mobiles = $user->where(array('is_robot' => 0, 'mobile' => array('like', '1%')))->getField('mobile', true);
        $mobiles = $user->where(array('type' => array('neq', 'robot'), 'mobile' => array('like', '1%')))->getField('mobile', true);
    }

    /**
     * 将user表中数据 转移至 new_user
     */
    // public function newSyncUser()
    // {   
    //     $temp_ar=array();
    //     set_time_limit(0);
    //     header("Content-Type: text/html; charset=utf-8");
    //     echo '嗯？不要瞎执行这个方法，会死人的，真的';
    //     die;

    //     $userObj = M('OldUser');
    //     $users = $userObj->field('id, mobile, password, nickname, realname, avatar, score, activity_time, is_robot, last_time, last_ip, reg_time, reg_ip, import')->select();

    //     foreach ($users as $user) {
    //         $temp_arr = [
    //             'id' => (int)$user['id'],
    //             'mobile' => $user['mobile'],
    //             'password' => $user['password'],
    //             'nickname' => $user['nickname'],
    //             'realname' => $user['realname'],
    //             'avatar' => $user['avatar'],
    //             'activity_time' => (int)$user['activity_time'],
    //             'score' => $user['score'],
    //             'remark' => $user['import'],
    //             'last_time' => $user['last_time'],
    //             'last_ip' => $user['last_ip'],
    //             'add_time' => $user['reg_time'],
    //             'add_ip' => $user['reg_ip'],
    //         ];

    //         $temp_arr['type'] = $user['is_robot'] == 1 ? 'robot' : '用户';

    //         try {
    //             M('User')->add($temp_arr);
    //         } catch (\Exception $e) {
    //             echo "用户{$user['mobile']}数据迁移失败...\n";
    //         }

    //         $temp_arr = null;
    //     }

    //     echo 'User表数据迁移完毕';
    //     die;
    // }

    /**
     * 将user 和 user_gravide数据迁移至 user_expand中
     */
    // public function newSyncUserExpand()
    // {
    //     set_time_limit(0);
    //     header("Content-Type: text/html; charset=utf-8");
    //     echo '嗯？不要瞎执行这个方法，会死人的，真的';
    //     die;

    //     $userObj = M('OldUser');
    //     $userGravideObj = M('OldUserGravide');

    //     $where = ['mobile' => ['like', '1%'], 'is_robot' => 0];
    //     $users = $userObj->field('id, sex, age, birthday, sid, qq, email, wechat, home_phone, work_phone, signature')->where($where)->select();

    //     foreach ($users as $user) {

    //         $temp_arr = [
    //             'id' => (int)$user['id'],
    //             'sex' => (int)$user['sex'],
    //             'age' => (int)$user['age'],
    //             'birthday' => (int)$user['birthday'],
    //             'sid' => $user['sid'],
    //             'qq' => $user['qq'],
    //             'email' => $user['email'],
    //             'wechat' => $user['wechat'],
    //             'home_phone' => $user['home_phone'],
    //             'work_phone' => $user['work_phone'],
    //             'signature' => $user['signature']
    //         ];

    //         $res = $userGravideObj->field('height, weight, anmelden_province_id, anmelden_city_id, anmelden_area_id,  
    //         anmelden_address, now_province_id, now_city_id, now_area_id, now_address, work_province_id, work_city_id,
    //         work_area_id, work_address, company, school, id_card_front, id_card_reverse, hukou_booklet_first, 
    //         hukou_booklet_self, edu, job, hospital_id')->where(['id' => (int)$user['id']])->find();

    //         if (!is_null($res)) {
    //             $temp_arr['height'] = $res['height'];
    //             $temp_arr['weight'] = $res['weight'];

    //             $temp_arr['anmelden_province_id'] = (int)$res['anmelden_province_id'];
    //             $temp_arr['anmelden_city_id'] = (int)$res['anmelden_city_id'];
    //             $temp_arr['anmelden_area_id'] = (int)$res['anmelden_area_id'];
    //             $temp_arr['anmelden_address'] = $res['anmelden_address'];

    //             $temp_arr['now_province_id'] = (int)$res['now_province_id'];
    //             $temp_arr['now_city_id'] = (int)$res['now_city_id'];
    //             $temp_arr['now_area_id'] = (int)$res['now_area_id'];
    //             $temp_arr['now_address'] = $res['now_address'];

    //             $temp_arr['work_province_id'] = (int)$res['work_province_id'];
    //             $temp_arr['work_city_id'] = (int)$res['work_city_id'];
    //             $temp_arr['work_area_id'] = (int)$res['work_area_id'];
    //             $temp_arr['work_address'] = $res['work_address'];

    //             $temp_arr['company'] = $res['company'];
    //             $temp_arr['school'] = $res['school'];

    //             $temp_arr['id_card_front'] = $res['id_card_front'];
    //             $temp_arr['id_card_reverse'] = $res['id_card_reverse'];
    //             $temp_arr['hukou_booklet_first'] = $res['hukou_booklet_first'];
    //             $temp_arr['hukou_booklet_self'] = $res['hukou_booklet_self'];

    //             $temp_arr['edu'] = (int)$res['edu'];
    //             $temp_arr['job'] = (int)$res['job'];
    //             $temp_arr['hospital_id'] = (int)$res['hospital_id'];
    //         }

    //         try {
    //             M('UserExpand')->add($temp_arr);
    //         } catch (\Exception $e) {
    //             echo "扩展表 用户{$user['id']}数据迁移失败...\n";
    //         }

    //         $temp_arr = null;
    //         $res = null;
    //     }

    //     echo 'UserExpand数据迁移完毕';
    //     die;
    // }

    /**
     * 将user_gravide表中数据 转移至 new_user_gravide
     */
    // public function newSyncUserGravide()
    // {
    //     set_time_limit(0);
    //     header("Content-Type: text/html; charset=utf-8");
    //     echo '嗯？不要瞎执行这个方法，会死人的，真的';
    //     die;

    //     $userGravideObj = M('OldUserGravide');
    //     $res = $userGravideObj->field('id, due_date, last_period_data, period_cycle, now_identity')->select();
    //     foreach ($res as $gravide) {
    //         $temp_arr = [
    //             'id' => (int)$gravide['id'],
    //             'due_date' => (int)$gravide['due_date'],
    //             'last_period_date' => (int)$gravide['last_period_data'],
    //             'period_cycle' => (int)$gravide['period_cycle'],
    //             'now_identity' => (int)$gravide['now_identity']
    //         ];

    //         try {
    //             M('UserGravide')->add($temp_arr);
    //         } catch (\Exception $e) {
    //             echo "用户{$gravide['id']}数据迁移失败...\n";
    //         }

    //         $temp_arr = null;
    //     }

    //     echo 'UserGravide数据迁移完毕';
    //     die;
    // }

    /**
     * 将user_doctor表中数据 转移至 new_user_doctor
     */
    // public function newSyncUserDoctor()
    // {
    //     set_time_limit(0);
    //     header("Content-Type: text/html; charset=utf-8");
    //     echo '嗯？不要瞎执行这个方法，会死人的，真的';
    //     die;

    //     $userDoctorObj = M('OldUserDoctor');
    //     $clinic = new ClinicModel();
    //     $doctors = $userDoctorObj->field('id, title_id, department_id, introduce, redundancy, treat, cover, doctor_seniority_cert,
    //     doctor_practice_cert, is_auth, authenticate_time, auth_select_cause, auth_detail_cause, is_rec, is_test, is_show')->select();

    //     foreach ($doctors as $doctor) {
    //         $temp_arr = [
    //             'id' => (int)$doctor['id'],
    //             'title_id' => (int)$doctor['title_id'],
    //             'department_id' => (int)$doctor['department_id'],
    //             'introduce' => $doctor['introduce'],
    //             'redundancy' => $doctor['redundancy'],
    //             'treat' => $doctor['treat'],
    //             'cover' => $doctor['cover'],
    //             'doctor_seniority_cert' => $doctor['doctor_seniority_cert'],
    //             'doctor_practice_cert' => $doctor['doctor_practice_cert'],
    //             'is_auth' => (int)$doctor['is_auth'],
    //             'authenticate_time' => (int)$doctor['authenticate_time'],
    //             'auth_select_cause' => (int)$doctor['auth_select_cause'],
    //             'auth_detail_cause' => $doctor['auth_detail_cause'],
    //             'is_rec' => (int)$doctor['is_rec'],
    //             'is_test' => (int)$doctor['is_test'],
    //             'is_show' => (int)$doctor['is_show'],
    //         ];

    //         $res = $clinic->field('cost, is_nb')->where(['user_id' => (int)$doctor['id']])->find();
    //         if (!is_null($res)) {
    //             $temp_arr['cost'] = $res['cost'];
    //             $temp_arr['is_pro'] = (int)$res['is_nb'];
    //         }

    //         try {
    //             M('UserDoctor')->add($temp_arr);
    //         } catch (\Exception $e) {
    //             echo "用户{$doctor['id']}数据迁移失败...\n";
    //         }

    //         $temp_arr = null;
    //         $res = null;
    //     }

    //     echo 'UserDoctor数据迁移完毕';
    //     die;
    // }

    // public function newSyncContacts()
    // {
    //     set_time_limit(0);
    //     header("Content-Type: text/html; charset=utf-8");
    //     echo '嗯？不要瞎执行这个方法，会死人的，真的';
    //     die;

    //     $contact = M('OldContacts');
    //     $contacts = $contact->field('name, user_id, mobile, relation')->select();
    //     foreach ($contacts as $c) {
    //         $temp_arr = [
    //             'type' => '联系人',
    //             'user_id' => (int)$c['user_id'],
    //             'name' => $c['name'],
    //             'mobile' => $c['mobile'],
    //             'relation' => (int)$c['relation']
    //         ];

    //         M('Contacts')->add($temp_arr);

    //         $temp_arr = null;
    //     }

    //     // 家庭成员
    //     $familyMemberObj = new FamilyMemberModel();
    //     $familys = $familyMemberObj->field('name, avatar, sex, height, weight, birthday, sid, mobile,
    //     relation, user_id')->select();
    //     foreach ($familys as $family) {
    //         $temp_arr = [
    //             'type' => '家庭成员',
    //             'user_id' => (int)$family['user_id'],
    //             'name' => $family['name'],
    //             'avatar' => $family['avatar'],
    //             'mobile' => $family['mobile'],
    //             'sex' => (int)$family['sex'],
    //             'sid' => $family['sid'],
    //             'birthday' => (int)$family['birthday'],
    //             'height' => $family['height'],
    //             'weight' => $family['weight'],
    //             'relation' => (int)$family['relation']
    //         ];

    //         M('Contacts')->add($temp_arr);

    //         $temp_arr = null;
    //     }

    //     // 儿童子女
    //     $childObj = new ChildInfoModel();
    //     $childs = $childObj->select();
    //     foreach ($childs as $child) {
    //         $temp_arr = [
    //             'type' => '子女',
    //             'user_id' => (int)$child['user_id'],
    //             'name' => $child['name'],
    //             'sex' => (int)$child['sex_key'],
    //             'birthday' => (int)$child['birthday'],
    //             'sid' => $child['idcard'],
    //             'nation' => $child['nation'],
    //             'birthplace' => $child['birthplace'],
    //             'birthhospital' => $child['birthhospital'],
    //             'nativeplace' => $child['nativeplace'],
    //             'province_id' => (int)$child['province_id'],
    //             'city_id' => (int)$child['city_id'],
    //             'area_id' => (int)$child['area_id'],
    //             'address' => $child['address'],
    //             'apgar' => (int)$child['apgar'],
    //             'jaundice' => (int)$child['jaundice'],
    //             'is_jaundice' => (int)$child['is_jaundice'],
    //             'add_time' => (int)$child['add_time'],
    //             'add_ip' => $child['add_ip'],
    //             'is_del' => (int)$child['is_del']
    //         ];

    //         switch ((int)$child['bloodtype_key']) {
    //             case 0:
    //                 $temp_arr['blood_type'] = '未知';
    //                 break;
    //             case 1:
    //                 $temp_arr['blood_type'] = 'O';
    //                 break;
    //             case 2:
    //                 $temp_arr['blood_type'] = 'A';
    //                 break;
    //             case 3:
    //                 $temp_arr['blood_type'] = 'B';
    //                 break;
    //             case 4:
    //                 $temp_arr['blood_type'] = 'AB';
    //                 break;
    //             default:
    //                 $temp_arr['blood_type'] = '其他';
    //                 break;
    //         }

    //         M('Contacts')->add($temp_arr);
    //         $temp_arr = null;
    //     }

    //     echo 'Contacts数据迁移完毕';
    //     die;
    // }

    /**
     * 同步余额
     */
    // public function newSyncMoney()
    // {
    //     set_time_limit(0);
    //     header("Content-Type: text/html; charset=utf-8");
    //     echo '嗯？不要瞎执行这个方法，会死人的，真的';
    //     die;

    //     $userDoctorObj = M('OldUserDoctor');
    //     $ids = $userDoctorObj->getField('id', true);

    //     foreach ($ids as $id) {
    //         $money = $userDoctorObj->where(['id' => (int)$id])->getField('money');

    //         M('User')->where(['id' => (int)$id])->setField('money', $money);
    //     }

    //     echo 'Money数据迁移完毕';
    //     die;
    // }

    /**
     * 同步is_base_full
     */
    // public function newSyncIsBaseFull()
    // {
    //     set_time_limit(0);
    //     header("Content-Type: text/html; charset=utf-8");
    //     echo '嗯？不要瞎执行这个方法，会死人的，真的';
    //     die;

    //     $userDoctorObj = M('OldUserDoctor');
    //     $res = $userDoctorObj->field('id, is_base_full')->select();

    //     foreach ($res as $k => $v) {
    //         M('UserDoctor')->where(['id' => (int)$v['id']])->setField('is_base_full', (int)$v['is_base_full']);
    //     }

    //     echo 'IsBaseFull数据迁移完毕';
    //     die;
    // }

    /**
     * 同步二维码
     */
    // public function newSyncQrcode()
    // {
    //     set_time_limit(0);
    //     header("Content-Type: text/html; charset=utf-8");
    //     echo '嗯？不要瞎执行这个方法，会死人的，真的';
    //     die;

    //     $userObj = M('OldUserGravide');
    //     $userDoctorObj = M('OldUserDoctor');
    //     $geneTestShareObj = new GeneTestShareModel();

    //     $user_qr_codes = $userObj->field('id, qr_code')->where(['qr_code' => ['neq', '']])->select();
    //     if (!is_null($user_qr_codes)) {
    //         foreach ($user_qr_codes as $user_qr_code) {
    //             $temp_data = [
    //                 'user_id' => (int)$user_qr_code['id'],
    //                 'type' => 'user',
    //                 'qr_code' => $user_qr_code['qr_code'],
    //                 'add_time' => ADD_TIME,
    //                 'add_ip' => ADD_IP
    //             ];
    //             M('Qrcode')->add($temp_data);
    //             $temp_data = null;
    //         }
    //     }

    //     $doctor_qr_codes = $userDoctorObj->field('id, qr_code')->where(['qr_code' => ['neq', '']])->select();
    //     if (!is_null($doctor_qr_codes)) {
    //         foreach ($doctor_qr_codes as $doctor_qr_code) {
    //             $temp_data = [
    //                 'user_id' => (int)$doctor_qr_code['id'],
    //                 'type' => 'doctor_rec',
    //                 'qr_code' => $doctor_qr_code['qr_code'],
    //                 'add_time' => ADD_TIME,
    //                 'add_ip' => ADD_IP
    //             ];
    //             M('Qrcode')->add($temp_data);
    //             $temp_data = null;
    //         }
    //     }

    //     $doctor_nipt_qr_codes = $userDoctorObj->field('id, nipt_qr_code')->where(['nipt_qr_code' => ['neq', '']])->select();
    //     if (!is_null($doctor_nipt_qr_codes)) {
    //         foreach ($doctor_nipt_qr_codes as $doctor_nipt_qr_code) {
    //             $temp_data = [
    //                 'user_id' => (int)$doctor_nipt_qr_code['id'],
    //                 'type' => 'doctor_nipt',
    //                 'qr_code' => $doctor_nipt_qr_code['nipt_qr_code'],
    //                 'add_time' => ADD_TIME,
    //                 'add_ip' => ADD_IP
    //             ];
    //             M('Qrcode')->add($temp_data);
    //             $temp_data = null;
    //         }
    //     }

    //     $user_nipt_qr_codes = $geneTestShareObj->field('id, qrcode, rec_link')->select();
    //     if (!is_null($user_nipt_qr_codes)) {
    //         foreach ($user_nipt_qr_codes as $user_nipt_qr_code) {
    //             $temp_data = [
    //                 'user_id' => (int)$user_nipt_qr_code['id'],
    //                 'type' => 'user_nipt',
    //                 'qr_code' => $user_nipt_qr_code['qrcode'],
    //                 'link' => $user_nipt_qr_code['rec_link'],
    //                 'add_time' => ADD_TIME,
    //                 'add_ip' => ADD_IP
    //             ];
    //             M('Qrcode')->add($temp_data);
    //             $temp_data = null;
    //         }
    //     }

    //     echo 'Qrcode数据迁移完毕';
    //     die;
    // }

    /**
     * 刷新直播信息缓存
     */
    // public function refLiveInfoCache()
    // {
    //     #file_put_contents('2.txt',time().'<br />',FILE_APPEND);
    //     $live_id = 55;
    //     $key = 'LIVE_INFO_OF_' . $live_id;


    //     $live = new LiveModel();
    //     $live_info = $live->where(['id' => $live_id])->find();
    //     $live_info['ref_time'] = time();
    //     S($key, $live_info, 3);
    // }

    /**
     * 刷新直播医生信息缓存
     */
    // public function refLiveDoctorInfoCache()
    // {
    //     $live_id = 55;
    //     $key = 'LIVE_INFO_OF_' . $live_id;
    //     $live_info = S($key);

    //     if ($live_info === false || empty($live_info)) {
    //         $this->refLiveInfoCache();
    //         $live_info = S($key);
    //     }

    //     $doctor_id = (int)$live_info['doctor_id'];

    //     $user = new UserModel();
    //     $doctor_info = $user->field('nickname, realname, avatar')->where(['id' => $doctor_id])->find();
    //     $doctor_info['ref_time'] = time();

    //     $doctor_cache_key = 'DOCTOR_INOF_OF_' . $doctor_id;
    //     S($doctor_cache_key, $doctor_info, 3600);
    // }

}